package com.moon.utils;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

public class RedisLock {

    private static final String LOCK_KEY = "redis_lock";
    private static final String LOCK_VALUE = "redis_lock_value";
    private static final int LOCK_EXPIRE_TIME = 30000; // 锁过期时间，单位为毫秒

    private Jedis jedis;

    public RedisLock(Jedis jedis) {
        this.jedis = jedis;
    }

    /**
     * 获取分布式锁
     */
    public boolean acquireLock() {
        SetParams params = new SetParams().nx().px(LOCK_EXPIRE_TIME);
        String result = jedis.set(LOCK_KEY, LOCK_VALUE, params);
        return "OK".equals(result);
    }

    /**
     * 释放分布式锁
     */
    public void releaseLock() {
        jedis.del(LOCK_KEY);
    }

    /**
     * 使用分布式锁执行业务逻辑
     */
    public void executeWithLock(Runnable runnable) {
        boolean lockAcquired = false;
        try {
            // 尝试获取分布式锁
            lockAcquired = acquireLock();
            if (lockAcquired) {
                // 获取锁成功，执行业务逻辑
                runnable.run();
            } else {
                // 获取锁失败，抛出异常或重试等处理
                throw new RuntimeException("Failed to acquire lock");
            }
        } finally {
            // 释放锁
            if (lockAcquired) {
                releaseLock();
            }
        }
    }
}